package codeine.servlets.version_label;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import codeine.jsons.labels.LabelJsonProvider;
import codeine.jsons.labels.ProjectLabelVersionJson;
import codeine.servlet.AbstractServlet;
import codeine.servlet.HtmlHeaderWriter;
import codeine.servlet.PermissionsManager;

import com.google.inject.Inject;

public class VersionsServlet extends AbstractServlet {
	private static final Logger log = Logger.getLogger(VersionsServlet.class);
	private static final long serialVersionUID = 1L;

	@Inject	private LabelJsonProvider versionLabelJsonProvider;
	@Inject private HtmlHeaderWriter htmlHeaderWriter;
	@Inject private PermissionsManager permissionsManager;
	
	@Override
	protected void myGet(HttpServletRequest request, HttpServletResponse response) {
		log.debug("VersionsServlet request");
		String projectName = request.getParameter("project");
		boolean readOnly = !permissionsManager.isModifiable(projectName, request);
		PrintWriter writer = getWriter(response);
		htmlHeaderWriter.writeHeader(request, response, projectName, projectName + " / versions");

		if (!readOnly){
			String line = "            <alert><div class=\"alertbar\"><ul>";
			line += "<li><input class='version' id='add_label' value='label' /></li>";
			line += "<li><input class='version' id='add_version' value='version' /></li>";
			line += "<li><input class='version' id='add_description' value='description' /></li>";
			line += "<li><button class='command' onclick='updateLabel(\""+projectName+"\")'>Add</button></li>";
			line += "</ul><br style=\"clear:left\"/></div></alert>";
			writer.println(line);
		}
		for (ProjectLabelVersionJson item : versionLabelJsonProvider.versions(projectName)) {
			String line2 = "            <alert><div class=\"alertbar\"><ul>";
			line2 += "<li><a class='nameg'>" + item.label() + "</a></li>";
			line2 += "<li><a class='nameg'>" + item.name() + "</a></li>";
			line2 += "<li><a class='nameg'>" + item.description() + "</a></li>";
			if (!readOnly){
				line2 += "<li><button class='command' onclick='deleteLabel(\""+projectName+"\", \""+item.label()+"\")'>Remove</button></li>";
			}
			line2 += "</ul><br style=\"clear:left\"/></div></alert>";
			writer.println(line2);
		}
		htmlHeaderWriter.writeFooter(response);
	}
	
	@Override
	protected void myPost(HttpServletRequest request, HttpServletResponse response) {
		ProjectLabelVersionJson versionLabelJson = readBodyJson(request, ProjectLabelVersionJson.class);
		versionLabelJsonProvider.updateLabel(versionLabelJson);
	}
	
	@Override
	protected void myDelete(HttpServletRequest request, HttpServletResponse response) {
		String projectName = request.getParameter("project");
		String label = request.getParameter("label");
		versionLabelJsonProvider.deleteLabel(label, projectName);
	}

}
